var express = require('express');
var router = express.Router();
var moment = require("moment")
var {aesDecrypt,checkSession} = require('../untils/index');
const { usersModel } = require('../untils/model');

var  {moviesModel} = require('../untils/model') 
/* GET home page. */
router.get('/', function (req, res, next) {
  console.log(req.session);
  res.render('index', {
    title: '超管系统',
    msg: "node so hard!",

    username:req.session.username,
    loginTime: req.session.loginTime,

  });
});
router.get('/login',  (req, res)=> {

  var username = req.query.username ? aesDecrypt(req.query.username) : ''
  console.log(username);
  res.render('login', { username});
});
router.get('/register', function (req, res, next) {
  res.render('register', {
    title: '超管系统',
    msg: "node so hard!",

    username:"",
    loginTime: req.session.loginTime,

  });
});
router.get('/my', function (req, res, next) {
  if(req.session.username){

    res.render('my', {
      title: '超管系统',
      msg: "node so hard!",
  
      username:req.session.username,
       loginTime: req.session.loginTime,

    })
  }else{
    res.send(`<script>alert('session失效，重新登录');location.href='/login'</script>`)

  }
});
router.get('/about', function (req, res, next) {
  if(req.session.username){

    res.render('about', {
      title: '超管系统',
      msg: "node so hard!",
  
      username:req.session.username,
      loginTime: req.session.loginTime,
    })
  }else{
    res.send(`<script>alert('session失效，重新登录');location.href='/login'</script>`)

  }
});
//注销
router.get('/logout',(req,res)=>{
  req.session.destroy(()=>{
    res.redirect("/") 
  })
})

//电影列表
router.get('/movie',(req,res)=>{
  checkSession(req,res,username=>{
    var query = req.query;
    console.log(query);
    var sortObj = {}
    var obj = {}
    if(query.keyword){
         //搜索
          obj = {
            $or:[
              {title :new RegExp(query.keyword)},
              {year :new RegExp(query.keyword)},
              {'rating.average' :new RegExp(query.keyword*1)},
              
            ]
          }
    }else{
      sortObj = query
    }
    moviesModel.find(obj,{_id:0})
    .sort(sortObj)
    .then(result=>{
      // console.log(result);
      res.render("movie",{username,result,title:"电影列表"})
    })
  })
})

module.exports = router;
